<template>
  <el-form ref="edit" :model="data" :rules="rules" label-width="100px">
    <el-form-item label="分类名称" prop="name">
      <el-input v-model="data.name" />
    </el-form-item>
    <el-form-item label="排序" prop="sort">
      <el-input v-model.number="data.sort" />
    </el-form-item>
    <el-form-item>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="updateCategory"> 确认 </el-button>
      </span>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { getCategoryDetailByIdApi, updateCategoryDetailApi } from '@/api/category.js'
import { ref, defineEmits, defineExpose } from 'vue'
import { ElMessage } from 'element-plus'

const emits = defineEmits(['closeEditDia'])

//表单
const data = ref({
  name: '',
  sort: null
})
const rules = {
  name: [{ required: true, message: '必填项', trigger: 'blur' }],
  sort: [{ required: true, message: '必填项', trigger: 'blur' }],
}

//获取菜品信息
const getCateDetail = async(id) => {
  const res = await getCategoryDetailByIdApi(id)
  data.value = res.data
}

const edit = ref()

//修改用户信息
const updateCategory = () => {
  edit.value.validate(async (isOk) => {
    if (!isOk) return
    try {
      const res = await updateCategoryDetailApi(data.value)
      if (res.code === 200) {
        ElMessage.success('修改成功')
        emits('editSuccess')
      } else {
        ElMessage.error(res.msg)
      }
    } catch (err) {
      console.log(err)
    }
    edit.value.resetFields()
  })
}
//关闭编辑弹窗
const close = () => {
  edit.value.resetFields()
  emits('closeEditDia')
}
defineExpose({
  getCateDetail
})
</script>
